查看原文
其他

.NET Core3.0 WebAPI 集成 Swagger 5.0

DotNet 2020-09-11

(给DotNet加星标,提升.Net技能


转自:cqinwn
cnblogs.com/cqinwn/p/10918206.html

在项目中引用Swashbuckle.AspNetCore和Swashbuckle.AspNetCore.Filters两个dll,在Startup中的ConfigureServices相关配置代码如下


services.AddSwaggerGen(options =>
{
string contactName = Configuration.GetSection("SwaggerDoc:ContactName").Value;
string contactNameEmail = Configuration.GetSection("SwaggerDoc:ContactEmail").Value;
string contactUrl = Configuration.GetSection("SwaggerDoc:ContactUrl").Value;
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = Configuration.GetSection("SwaggerDoc:Version").Value,
Title = Configuration.GetSection("SwaggerDoc:Title").Value,
Description = Configuration.GetSection("SwaggerDoc:Description").Value,
Contact = new OpenApiContact { Name = contactName, Email = contactNameEmail, Url =new Uri(contactUrl)},
License = new OpenApiLicense { Name = contactName, Url = new Uri(contactUrl) }
});

var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "Yuebon.WebApi.xml");
options.IncludeXmlComments(xmlPath);
options.DocumentFilter<HiddenApiFilter>(); // 在接口类、方法标记属性 [HiddenApi],可以阻止【Swagger文档】生成
options.OperationFilter<AddHeaderOperationFilter>("correlationId", "Correlation Id for the request", false); // adds any string you like to the request headers - in this case, a correlation id
options.OperationFilter<AddResponseHeadersFilter>();
options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
options.OperationFilter<SecurityRequirementsOperationFilter>();
//给api添加token令牌证书
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey
});
});


两个重点:


1、options.DocumentFilter<HiddenApiFilter>();定义那些接口方法被隐藏


2、启用oauth2安全授权访问api接口


options.OperationFilter<SecurityRequirementsOperationFilter>();
//给api添加token令牌证书
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey
});


其中使用SecurityRequirementsOperationFilter需要在控制器头部加[Authorization]或则方法头部加[Authorization],如下:


[Authorize]
public class TokenController : ControllerBase


或者

[Authorize("Customer")]
public PersonResponse GetPerson([FromBody]PersonRequest personRequest)


这样在每个接口才会有小锁出现。



更多介绍请参考https://github.com/domaindrivendev/Swashbuckle.AspNetCore和https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters


推荐阅读

(点击标题可跳转阅读)

.NET Core微服务工作流

.NET Core微服务权限系统

站点部署IIS配置优化指南


看完本文有收获?请转发分享给更多人

关注「DotNet」加星标,提升.Net技能 

好文章,我在看❤️

    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存